package main

import (
	"time"
	"fmt"
)

//限速 是控制资源利用率和维护服务质量的重要机制
//支持goroutines, channels, tickers的速率限制
func main() {
	// 5个请求
	requests := make(chan int, 5)
	for i := 1; i <= 5; i++ {
		requests <- i
	}
	close(requests)
	//每秒处理一个请求
	limiter := time.Tick(time.Second)
	for req := range requests {
		<-limiter
		fmt.Println("requests", req, time.Now())
	}

	//3个缓冲池
	//费率限制计划中允许短时间爆发请求，同时保留整体费率限制
	burstyLimiter := make(chan time.Time, 3)
	for i := 0; i < 3; i++ {
		burstyLimiter <- time.Now()
	}
	go func() {
		for t := range time.Tick(time.Second) {
			burstyLimiter <- t
		}
	}()

	//初始化请求
	burstyRequests := make(chan int, 5)
	for i := 1; i <= 5; i++ {
		burstyRequests <- i
	}
	close(burstyRequests)
	//处理请求，由于可突发速率限制，立即为前3个服务，然后为剩余的2个服务，每个延迟约1秒。
	for req := range burstyRequests {
		<-burstyLimiter
		fmt.Println("burstyRequests", req, time.Now())
	}
}
